package designpattern.proxy;

import net.sf.cglib.proxy.Enhancer;

import java.lang.reflect.Proxy;

/**
 * 代理工厂类
 * @Author Antony
 * @Since 2018/5/11 16:11
 */
public class ProxyFactory {

    /**
     * 工厂方法，获取JDKProxy对象
     * @param proxyObject
     * @return
     */
    public static Object createJDKProxyInstance(Object proxyObject){
        JDKProxy jdkProxy = new JDKProxy(proxyObject);
        return Proxy.newProxyInstance(proxyObject.getClass().getClassLoader(), proxyObject.getClass().getInterfaces(), jdkProxy);
    }

    public static Object createJDKProxyInstance(Object proxyObject, String proxyName){
        JDKProxy jdkProxy = new JDKProxy(proxyObject, proxyName);
        return Proxy.newProxyInstance(proxyObject.getClass().getClassLoader(), proxyObject.getClass().getInterfaces(), jdkProxy);
    }


    /**
     * 工厂方法，获取cglibProxy对象
     * @param proxyObject
     * @return
     */
    public static Object createCGlibProxyInstance(Object proxyObject){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(proxyObject.getClass());
        enhancer.setCallback(new CGlibProxy(proxyObject));
        return enhancer.create();
    }

    public static Object createCGlibProxyInstance(Object proxyObject, String proxyName){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(proxyObject.getClass());
        enhancer.setCallback(new CGlibProxy(proxyObject, proxyName));
        return enhancer.create();
    }

}
